import streamlit as st
from typing import Dict

from src.core.dsl_interpreter import DSLInterpreter
from src.scripts.example_scripts import get_all_scripts, get_script_by_name

# ----------------------
# Session-state helpers
# ----------------------
def get_interpreter() -> DSLInterpreter:
    if 'interpreter' not in st.session_state:
        st.session_state.interpreter = DSLInterpreter()
    return st.session_state.interpreter


def ensure_defaults():
    if 'current_script' not in st.session_state:
        st.session_state.current_script = 'combined'
    if 'loaded' not in st.session_state:
        st.session_state.loaded = False
    if 'user_name' not in st.session_state:
        st.session_state.user_name = 'fusihan1'
    if 'messages' not in st.session_state:
        st.session_state.messages = []


# ----------------------
# App start
# ----------------------
ensure_defaults()
interpreter = get_interpreter()

st.set_page_config(page_title='DSL 智能客服 Demo', page_icon='🤖', layout='centered')
st.title('智能客服机器人（DSL Demo）')

# ----------------------
# Sidebar - settings
# ----------------------
with st.sidebar:
    st.header('设置')

    # 选择并加载脚本
    scripts: Dict[str, str] = get_all_scripts()
    selected_script = st.selectbox(
        '选择脚本',
        options=list(scripts.keys()),
        index=list(scripts.keys()).index(st.session_state.current_script)
            if st.session_state.current_script in scripts else 0,
        help='选择不同脚本以切换机器人的行为'
    )

    if st.button('加载脚本', use_container_width=True):
        script_text = get_script_by_name(selected_script)
        ok = interpreter.load_script(script_text)
        if ok:
            st.session_state.current_script = selected_script
            st.session_state.loaded = True
            # 切换脚本时清空对话与记忆，避免上下文混淆
            st.session_state.messages = []
            interpreter.conversation_history.clear()
            interpreter.clear_longmemory()
            st.success(f'已加载脚本：{selected_script}')
        else:
            st.error('脚本加载失败，请检查脚本内容')

    st.markdown('---')
    st.subheader('登录用户')
    preset_user = st.selectbox(
        '选择或输入用户名',
        options=['fusihan1', 'fusihan2', 'fusihan3', '自定义...'],
        index=0
    )
    if preset_user == '自定义...':
        st.session_state.user_name = st.text_input('输入自定义用户名', value='guest')
    else:
        st.session_state.user_name = preset_user

    st.markdown('---')
    st.caption('当前脚本：' + (st.session_state.current_script or '未选择'))

# ----------------------
# Chat history
# ----------------------
if not st.session_state.loaded:
    st.info('请先在左侧选择脚本并点击“加载脚本”。默认推荐加载 combined（综合脚本）。')

# 展示历史消息
for m in st.session_state.messages:
    st.chat_message(m['role']).markdown(m['content'])

# 输入消息
prompt = st.chat_input('请输入消息（例如：你好 / 查询订单 / 我要取消订单 F1-002 / 技术问题 / 转人工）')
if prompt:
    # 显示并记录用户消息
    st.chat_message('user').markdown(prompt)
    st.session_state.messages.append({'role': 'user', 'content': prompt})

    # 调用解释器
    user_name = st.session_state.user_name or 'guest'
    reply = interpreter.process_user_input(user_name, prompt)

    # 显示并记录机器人回复
    st.chat_message('assistant').markdown(reply)
    st.session_state.messages.append({'role': 'assistant', 'content': reply})

# ----------------------
# 订单展示模块
# ----------------------
st.markdown('---')
st.subheader('订单列表（当前用户）')

try:
    user_vars = interpreter.get_user_info(st.session_state.user_name)
    orders = user_vars.get_order_list() if user_vars else []

    # 刷新按钮（重新读取内存中的订单，不触发网络请求）
    cols = st.columns([1, 3])
    with cols[0]:
        if st.button('刷新订单'):  # 触发一次 rerun 即可
            st.experimental_rerun()

    if orders:
        # 构造表格数据
        rows = [
            {
                '订单ID': o.order_id,
                '商品': o.order_type,
                '金额': o.order_amount,
                '日期': o.order_date,
                '状态': o.order_status,
            }
            for o in orders
        ]
        st.table(rows)
    else:
        st.info('当前用户暂无订单。')
except Exception as e:
    st.error(f'读取订单失败：{e}')

# ----------------------
# 调试信息
# ----------------------
st.markdown('---')
with st.expander('调试信息', expanded=False):
    st.write('当前用户：', st.session_state.user_name)
    st.write('当前脚本：', st.session_state.current_script)
    try:
        user_vars = interpreter.get_user_info(st.session_state.user_name)
        cnt = len(user_vars.get_order_list()) if user_vars else 0
        st.write('会话订单数量：', cnt)
    except Exception as e:
        st.write(f'读取失败: {e}')
